﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QtConcurrent/QtConcurrentRun>
#include <QtConcurrent/QtConcurrent>
#include <QFileDialog>
#include <qmessagebox.h>
#include "mythreadpool.h"
//#include "HString.h"

void test()
{
    QString s = "[7][2025-06-12][10:16:53][T427796032][source/HEnvironment.cpp                 ][0936][I]session_id:1,uid:1000,user:cidi,seat:seat0";
    QStringList lists = s.split("][");
    qDebug()<<lists;
    if(lists.size() == 7)
    {
        lists[0].remove(0,1);
        int pos = lists[6].indexOf("]");
        QString tail  = lists[6].mid(pos + 1);
        lists[6].remove(pos,lists[6].length()- pos);
        lists.append(tail);
    }
    qDebug()<<lists;
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    init_datas();
    init_menus();
    init_connects();
    test();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    static bool bFirst = true;
    if(bFirst)
    {
        bFirst = false;
        return;
    }

    int nCount = model->columnCount();
    int iWide = ui->tb_logview->width();
    int iCell = iWide/nCount;

    for (int i = 0;i < nCount; i++) {
        ui->tb_logview->setColumnWidth(i,iCell);
    }
}

void MainWindow::init_datas()
{
    model = new LogModel(this);
    ui->tb_logview->setModel(model);
    ui->progressBar->setValue(0);
    model->columnCount();

    m_lb_dir = new QLabel(this);
    ui->statusBar->addWidget(new QLabel("路径："));
    ui->statusBar->addWidget(m_lb_dir);
    qDebug() << "Max threads:" << QThreadPool::globalInstance()->maxThreadCount();

}

void MainWindow::init_menus()
{
    QAction* p_action_open = ui->menu_file->addAction(QStringLiteral("打开"));
    connect(p_action_open,SIGNAL(triggered()),this,SLOT(on_action_open()));
}

void MainWindow::init_connects()
{

}

void MainWindow::add_load_file_task(QString filename)
{
    TaskNotifier *notifier = new TaskNotifier(filename,this);
    LoadFileTask *fileTask = new LoadFileTask(notifier);

    qRegisterMetaType<TASK_STATUS>("TASK_STATUS");
    qRegisterMetaType<QVector<LogEntry>>("QVector<LogEntry>");
    connect(notifier,SIGNAL(taskFinished(TASK_STATUS,QString)),this,SLOT(on_task_finish(TASK_STATUS,QString)));
    connect(notifier,SIGNAL(taskLineInfo(QVector<LogEntry>)),this,SLOT(on_task_lineinfo(QVector<LogEntry>)));

    fileTask->setAutoDelete(true);
    QThreadPool::globalInstance()->start(fileTask);

}


void MainWindow::on_action_open()
{
    qDebug()<<__func__<<" begin";

    QString dirPath = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "",
                                                           QFileDialog::ShowDirsOnly);
   if (dirPath.isEmpty())
       return;

   QDir dir(dirPath);
   QStringList filters {"*.log", "*.txt"};
   dir.setNameFilters(filters);

   QFileInfoList files = dir.entryInfoList();

   if (files.isEmpty()) {
       qDebug() << "No files found.";
       return;
   }

   QStringList list;
    for (const QFileInfo &fileInfo : files) {
       qDebug() << "Found file:" << fileInfo.absoluteFilePath();
       qDebug() << "Found file:" << fileInfo.fileName();
       list.append(fileInfo.fileName());
    }
    ui->cb_filelist->clear();
    ui->cb_filelist->addItems(list);
    ui->cb_filelist->addItem("all");
    m_lb_dir->setText(dirPath);

    QString filePath = QDir(dirPath).filePath(ui->cb_filelist->currentText());
    qDebug()<<"filePath "<<filePath;
    if(QFile::exists(filePath))
    {
        add_load_file_task(filePath);
    }
}



void MainWindow::on_cb_filelist_currentTextChanged(const QString &arg)
{
    QString dirPath = m_lb_dir->text();

    if(dirPath.isEmpty())
    {
        QMessageBox::warning(this,"tip","dir is empty!!!");
        return;
    }

    if(arg == "all")
    {
        QDir dir(dirPath);
        QStringList logFiles = dir.entryList(QStringList() << "*.log" << "*.txt", QDir::Files);
        model->clear();
        foreach (const QString &file, logFiles) {
            add_load_file_task(dir.absoluteFilePath(file));
        }
    }
    else
    {
        QString filePath = QDir(dirPath).filePath(arg);
        if(QFile::exists(filePath))
        {
            model->clear();
            add_load_file_task(filePath);
        }
    }



}

void MainWindow::on_task_finish(TASK_STATUS status, QString info)
{
    Q_UNUSED(status);
    ui->statusBar->showMessage(info);
}

void MainWindow::on_task_lineinfo(QVector<LogEntry> vec)
{
    model->addEntries(vec);
}


void MainWindow::on_pb_search_clicked()
{
    QString str_threadid = ui->le_threadid->text().trimmed();
    QString str_level = ui->le_loglevel->text().trimmed();
    QString str_keyword = ui->le_keyword->text().trimmed();

    model->setFilter(str_threadid,str_level,str_keyword);
}
